import torch
import torch.nn as nn
import torch.nn.functional as F
from collections import OrderedDict


def _BN_ReLu_Conv(in_channels, out_channels, k_size, stride, padding, inplace, bias) -> nn.Sequential:
    return nn.Sequential(
        nn.BatchNorm2d(in_channels),
        nn.ReLU(inplace=inplace),
        nn.Conv2d(in_channels, out_channels, k_size, stride, padding, bias=bias)
    )


class _DenseBlock(nn.ModuleDict):
    def __init__(self, num_layers, in_channels, growth_rate, bn_rate):
        super(_DenseBlock, self).__init__()
        for i in range(num_layers):
            self.add_module(f"denselayer{i}", nn.Sequential(
                _BN_ReLu_Conv(in_channels + i * growth_rate, bn_rate * growth_rate, 1, 1, 0, False, False),
                _BN_ReLu_Conv(bn_rate * growth_rate, growth_rate, 3, 1, 1, False, False)
            ))

    def forward(self, features):
        features = [features]
        for name, layer in self.items():
            concat_features = torch.concat(features, 1)
            new_features = layer(concat_features)
            features.append(new_features)
        return torch.concat(features, 1)


class _Transition(nn.Sequential):
    def __init__(self, in_channels, out_channels):
        super(_Transition, self).__init__()
        self.add_module("bn_relu_conv", _BN_ReLu_Conv(in_channels, out_channels, 1, 1, 0, True, False))  # compress
        self.add_module("pool", nn.AvgPool2d(2, 2))  # downsample


class DesNet(nn.Module):
    def __init__(self, growth_rate=24, bn_rate=2, layers=(3, 4, 3), num_classes=10):
        super().__init__()
        num_features = growth_rate * 2
        self.features = nn.Sequential(
            OrderedDict([
                ("conv0", nn.Conv2d(3, num_features, 3, 1, 1, bias=False)),
                ("norm0", nn.BatchNorm2d(num_features=num_features)),
                ("relu0", nn.ReLU(inplace=True)),
                ("pool0", nn.MaxPool2d(3, 2, 1))  # 16 * 16
            ]))

        for i, num_layers in enumerate(layers):
            self.features.add_module(f"denseblock{i}", _DenseBlock(num_layers, num_features, growth_rate, bn_rate))
            num_features = num_features + num_layers * growth_rate
            if i == len(layers) - 1:
                break
            self.features.add_module(f"transition{i}", _Transition(num_features, num_features // 2))  # compression theta=0.5
            num_features = num_features // 2

        self.features.add_module("norm5", nn.BatchNorm2d(num_features))
        self.classifier = nn.Linear(num_features, num_classes)

    def forward(self, x):
        features = self.features(x)
        out = F.relu(features, inplace=True)
        out = F.adaptive_avg_pool2d(out, (1, 1))
        out = torch.flatten(out, 1)
        return self.classifier(out)


class BasicBlock(nn.Module):
    def __init__(self, in_channel, out_channel, stride=1, downsample=None):
        super(BasicBlock, self).__init__()
        self.conv1 = nn.Conv2d(in_channels=in_channel,
                               out_channels=out_channel,
                               kernel_size=3,
                               stride=stride,
                               padding=1,
                               bias=False)
        self.bn1 = nn.BatchNorm2d(out_channel)
        self.relu = nn.ReLU()
        self.conv2 = nn.Conv2d(in_channels=out_channel,
                               out_channels=out_channel,
                               kernel_size=3,
                               stride=1,
                               padding=1,
                               bias=False)
        self.bn2 = nn.BatchNorm2d(out_channel)
        self.downsample = downsample

    def forward(self, x):
        identity = x
        if self.downsample is not None:
            identity = self.downsample(x)
        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)
        out = self.conv2(out)
        out = self.bn2(out)
        out += identity
        out = self.relu(out)
        return out


class ResNet(nn.Module):
    def __init__(self, blocks_num=(2, 2, 2), num_classes=10, bottle_neck=False):
        super(ResNet, self).__init__()
        self.in_channel = 32
        self.conv1 = nn.Conv2d(3, self.in_channel, kernel_size=3, stride=1, padding=1, bias=False)
        self.bn1 = nn.BatchNorm2d(self.in_channel)
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) # 16 * 16
        self.block1 = self._make_layer(BasicBlock, 32, blocks_num[0])   # 16 * 16
        self.block2 = self._make_layer(BasicBlock, 64, blocks_num[1], stride=2)    # 8 * 8
        self.block3 = self._make_layer(BasicBlock, 128, blocks_num[2], stride=2)   # 4 * 4
        self.avgpool = nn.AdaptiveAvgPool2d((1, 1))
        self.fc = nn.Linear(128, num_classes)

    def _make_layer(self, block, channel, block_num, stride=1):
        downsample = None
        if stride != 1 or self.in_channel != channel:
            downsample = nn.Sequential(
                nn.Conv2d(self.in_channel, channel, kernel_size=1, stride=stride, bias=False),
                nn.BatchNorm2d(channel))
        layers = []
        layers.append(
            block(self.in_channel,
                  channel,
                  downsample=downsample,
                  stride=stride)
        )
        self.in_channel = channel
        for _ in range(1, block_num):
            layers.append(block(self.in_channel, channel))

        return nn.Sequential(*layers)

    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)
        x = self.block1(x)
        x = self.block2(x)
        x = self.block3(x)
        x = self.avgpool(x)
        x = torch.flatten(x, 1)
        x = self.fc(x)
        return x

if __name__ == '__main__':
    net = DesNet()
    print(net)
    # x = torch.rand((1, 3, 32, 32))
    # out = net(x)
    # print(out)